package com.itcast.flink.window.count;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

/**
 * Flink Window窗口计算：滑动计数窗口案例演示【每4条数据对最近3条数据进行统计计算】
 *  * @author xuanyu
 * @author lilulu
 */
public class SlidingCountWindowDemoV2 {
    public static void main(String[] args) throws Exception {
        // 1. 执行环境-env
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 2. 数据源-source
        DataStreamSource<String> source = env.socketTextStream("node1", 9999);
        // 3. 数据转换-transformation
        SingleOutputStreamOperator<String> windowStream = source.filter(line -> line.trim().length() > 0)
                .map(new MapFunction<String, Integer>() {
                    @Override
                    public Integer map(String s) throws Exception {
                        System.out.println("item:" + s);
                        return Integer.parseInt(s);
                    }
                }).countWindowAll(3, 4).apply(new AllWindowFunction<Integer, String, GlobalWindow>() {
                    @Override
                    public void apply(GlobalWindow globalWindow, Iterable<Integer> iterable, Collector<String> collector) throws Exception {
                        int sum = 0;
                        for (Integer integer : iterable) {
                            sum += integer;
                        }
                        collector.collect("sum" + sum);
                    }
                });
        // 4. 数据终端-sink
        windowStream.printToErr();
        // 5. 触发执行-execute
        env.execute("SlidingCountWindowDemoV2");
    }
}